package com.qf.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis实现分布式锁工具类
 * @author zhaojian
 */
@Component
public class RedisLockUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 加锁
     * @param key
     * @param value 
     * @param second 锁定时间, 单位为秒
     * @return
     */
    public boolean lock(String key, String value, int second){
        return redisTemplate.opsForValue().setIfAbsent(key,value,second, TimeUnit.SECONDS);
    }


    /**
     * 解锁
     * @param key
     */
    public void unlock(String key){
        redisTemplate.delete(key);
    }
}